package com.scs.application.modules.sys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.IPUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.sys.dto.UserSelectDTO;
import com.scs.application.modules.sys.entity.User;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.sys.security.UserPrincipal;
import com.scs.application.modules.sys.service.MenuService;
import com.scs.application.modules.sys.service.UserService;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController extends CrudController<UserService, User> {
    @Value("${system.UserDefaultPassword}")
    private String userDefaultPassword;
    @Autowired
    MenuService menuService;

    @GetMapping("/tree")
    public RestResult selectById() {
        List<UserSelectDTO> tree = service.getUserTree();
        return RestResult.ok("get user success", tree);
    }

    /**
    * @Description： home查询用户各类初始化信息使用
    */
    @GetMapping("/info")
    public RestResult info(HttpServletRequest request) {
        Map<String, Object> result = Maps.newHashMap();
        User user = service.getById(UserUtils.currentUser().getId());
        if (user == null ) {
            throw new BusinessException("用户不存在或者已被删除");
        }
        //用户信息
        UserPrincipal user1 = UserUtils.currentUser();
        user1.setIpAddrCustom(IPUtils.getIpAddr(request));
        result.put("currentUser", user1);
        //可用菜单列表
        result.put("menuList", menuService.getUserMenu());

        //用户信息
        result.put("user", user);
        return RestResult.ok("获取成功", result);
    }

    @PostMapping("/password")
    public RestResult password(@RequestBody Map<String, String> para) {
        service.password(para.get("oldPassword"), para.get("newPassword"));
        return RestResult.ok("修改密码成功");
    }

    @PostMapping("/resetPwd")
    public RestResult resetPwd(@RequestBody Map<String, String> para) {
        service.resetPwd(para.get("id"));
        return RestResult.ok("重置密码成功");
    }

    /**
     * 上传头像
     * @param file
     * @param userId
     * @return
     */
    @PostMapping("/uploadPicture")
    public RestResult uploadPicture(@RequestParam("file") MultipartFile file, @RequestParam("userId") String userId) {
        return RestResult.ok("上传文件成功!", service.uploadPicture(file, userId));
    }

    @GetMapping("/listByOffice")
    public RestResult listByOffice(){
        QueryContext queryContext = QueryContextHolder.currentContext();
        Object officeId = queryContext.getParams().get("office_id");
        List<User> userList = service.list(Wrappers.<User>query().eq("office_id", officeId));
        return RestResult.ok("查询成功", userList);
    }

    /**
     * 获取角色用户
     * @return
     */
    @GetMapping(value = "/listByRole")
    public RestResult listByRole(){
        QueryContext queryContext = QueryContextHolder.currentContext();
        Object roleId = queryContext.getParams().get("role_id");
        if (roleId == null){
            throw new BusinessException("数据异常");
        }
        List<User> models = service.listByRole(roleId.toString());
        return RestResult.ok("获取角色用户成功！",models);
    }

    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody User entity) {
        String msgAppend="";
        if(entity.getId() == null){
            msgAppend=",默认密码【"+userDefaultPassword+"】";
        }
        boolean isOk = service.saveOrUpdate(entity);

        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        return RestResult.ok("数据保存成功"+msgAppend,  entity);
    }

    /**
     * 角色维护-编辑界面-左侧用户列表
     */
    @GetMapping("/pageForRoleEdit")
    public PageResult pageForRoleEdit(@RequestParam Map<String, Object> reqData) {
        QueryContext queryContext = QueryContextHolder.currentContext();

        Map<String, Object> userParam =Maps.newHashMap();
        //固定参数
        if(reqData.containsKey("userParam")){
            JSONObject ob = JSON.parseObject(reqData.get("userParam")+"");
            userParam= Maps.newHashMap(ob);
        }

        //排除掉已添加过的用户
        String roleId = (String)userParam.get("roleId");
        if (StringUtils.isNotBlank(roleId)){
            queryContext.getWrapper().notInSql("id","select user_id from sys_role_user where role_id = '"+roleId+"'");
        }

        IPage pageResult = service.page(queryContext);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }


    /**
    * @Description： 更新用户操作状态
    */
    @PostMapping(value="/updateUserState")
    public RestResult updateUserState(@RequestBody Map<String, String> param){
        service.updateUserState(param.get("type"),UserUtils.currentUser().getId(),param.get("stateKey"),param.get("stateValue"));
        return RestResult.ok();
    }

    /**
     * @Description： 获取当前更路用户操作状态
     */
    @GetMapping(value="/getCurrentUserState")
    public RestResult getCurrentUserState(){
        return RestResult.ok("获取成功",service.getById(UserUtils.currentUser().getId()));
    }

}
